/*
 * @Author: your name
 * @Date: 2021-06-08 11:11:01
 * @LastEditTime: 2021-06-16 17:52:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \UDP\SERVER_\parse->cpp
 */

#include "parse.h"

void Parse::parse_Message(char* buf)
{
    //强转buf
    info* tinfo = (info*)buf;
    cout << "----------------------" << endl;
	cout << "com_src:" << tinfo->com_src << endl
		<< "opcode:" << tinfo->opcode << endl;
	printf("name:%s\n",tinfo->name);
	printf("passwd:%s\n",tinfo->passwd);
	printf("type:%d\n",tinfo->type); 
	printf("balance:%lf\n",tinfo->balance);


	if(tinfo->cartnum < 10 && tinfo->type == _LOGIN_CONSUMER)
	{
		cout << "购物车信息如下" << endl;
		cout << "购物车商品种类：" << tinfo->cartnum << endl;
		for(int i=0; i<tinfo->cartnum; i++)
		{
			cout << "商品编号：" << tinfo->cartIndexArray[i] << " 数目:" << tinfo->indexNumArray[i] << endl;
		}
	}
	cout << "----------------------" << endl;
}

void Parse::deal_Register(char* recv_buf,char* send_buf)
{
	//接收到的信息
	info* r_info = (info*)recv_buf;

	//取得recv_buf的用户名与密码
	string name = r_info->name;
	string passwd = r_info->passwd;

	//写入日志
	Log tlog;
	tlog.get_Log_Ptr() << "注册请求:" <<  name << endl;
	cout << name << " " << passwd << endl;

	//判断用户名是否已经存在
	string sql = "select * from user where ";
	sql = sql + "username = '" + name + "';";
	char* reg_sql = (char*)sql.data();

	//根据查询到的结果进行反馈
	info* s_info = (info*)send_buf;
	bool isfind = Database().query_Table(reg_sql);
	//数据库中存在该数据
	if(isfind)
	{
		tlog.get_Log_Ptr() << "用户名重复 '" << name << "' 注册失败" << endl;
		s_info->status_code = _REGISTER_ERROR;
	}
	//数据库不存在该用户名
	else
	{
		//将该用户名以及密码写入数据库
		string insert_sql = "insert into user (username,passwd,type,balance,cartnum,cartIndexArray,indexNumArray) values";
		insert_sql = insert_sql + "('" + name + "','" + passwd + "',1,0,0,'0','0')";
		char* ins_sql = (char*)insert_sql.data();
		// printf("insert sql:%s\n",ins_sql); 
		bool isInsert = Database().query_SQL(ins_sql);
		if(isInsert)
		{
			s_info->status_code = _REGISTER_OK;
			tlog.get_Log_Ptr() << name << "注册成功" << endl;
		}
		else
		{
			s_info->status_code = _REGISTER_ERROR;
			cout << "插入失败" << endl;
		}
	}
}

void Parse::deal_Login(char* recv_buf,char* send_buf)
{
	//接收到的信息
	info* r_info = (info*)recv_buf;
	
	//对反馈进行处理
	//取得recv_buf的用户名与密码
	string name = r_info->name;
	string passwd = r_info->passwd;

	//写入日志
	Log tlog;
	tlog.get_Log_Ptr() << "用户 " << name << " 请求登录" << endl;

	//构造sql语句
	string sql = "select * from user where ";
	sql = sql + "username = '" + name + "' AND " + "passwd = '" + passwd + "';";
	//cout << "sql:" << sql << endl;

	//转换为char*
	char* str_sql = (char*)sql.data();
	// cout << "转换为char*:";
	// printf("%s\n",str_sql);


	//根据查询到的结果进行反馈
	info* s_info = (info*)send_buf;

	//返回账户名，密码，用户类型，余额，购物车数目，购物车商品下标，购物车对应商品数目
	//构造好数据库语句后，执行
	int type = Database().verify_User_Passwd(str_sql,(*s_info));
	
	//写入日志
	switch (type)
	{
	case _LOGIN_ERROR:
		tlog.get_Log_Ptr() << "登录码错误，登录失败" << endl;
		break;
	case _LOGIN_MERCHANT:
		tlog.get_Log_Ptr() << "商户登:" << name <<"录成功" << endl;
		break;
	case _LOGIN_CONSUMER:
		tlog.get_Log_Ptr() << "消费者:" << name << "登录成功" << endl;
		break;
	default:
		break;
	}

	//反馈类型
	s_info->com_src = SERVER_SEND;
	s_info->opcode = _LOGIN;
	
	// this->parse_Message(send_buf);
	//此时回送包已经构造完毕
}

void Parse::deal_Query_All_Commodity(char* recv_buf,char* send_buf)
{
	//接收到的信息,这个不重要
	info* r_info = (info*)recv_buf;
	
	//返回的信息
	info* s_info = (info*)send_buf;


	//日志
	Log tlog;
	tlog.get_Log_Ptr() << "查询商品信息请求" << endl;

	//从数据库将信息拿入到s_info
	int num = Database().get_All_Commodity_Info(*s_info);

	{
		// cout << "写入信息重读" << endl;
		// for(int i=0; i<num; i++)
		// {
		// 	cout <<s_info->com_array[i].identifier << "\t"
		// 		<< s_info->com_array[i].cname << "\t"
		// 		<< s_info->com_array[i].brand << "\t"
		// 		<< s_info->com_array[i].classify << "\t"
		// 		<< s_info->com_array[i].price << "\t"
		// 		<< s_info->com_array[i].remain << "\t"
		// 		<< s_info->com_array[i].frozen << "\t"
		// 		<< s_info->com_array[i].others << endl;
		// }
	}
	
	//根据num返回信息
	s_info->com_num = num;
	tlog.get_Log_Ptr() << "已经应答查询商品信息请求：" << num << "种商品" << endl;
}

void Parse::deal_Recharge(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;

	info* r_info = (info*)recv_buf;
	//验证账户密码（暂时省略这一步）
	string name = r_info->name;
	string passwd = r_info->passwd;
	tlog.get_Log_Ptr() << name << "请求充值:" << r_info->newbalance << " 元" << endl;
	//获取充值后的余额
	double charge_num = r_info->newbalance + r_info->balance;
	string s_num = std::to_string(charge_num);
	// cout << "s_num:" << s_num << endl;
	//构造SQL语句
	string sql = "update user set balance = ";
	sql = sql + s_num + " where username = '" + name + "' and passwd = '" + passwd + "';";
	// cout << "充值语句:" << sql << endl;
	//更新数据库
	bool isExe = Database().query_SQL((char*)sql.data());

	//根据查询到的结果进行反馈
	info* s_info = (info*)send_buf;

	//执行成功
	if(isExe)
	{
		tlog.get_Log_Ptr() << name << "充值成功,余额为:" << charge_num << endl;
		s_info->status_code = _REGISTER_OK;
		s_info->balance = charge_num;
	}
	else
	{
		tlog.get_Log_Ptr() << name << "充值失败" << endl;
		s_info->status_code = _RECHARGE_ERROR;
	}
}

void Parse::deal_Change_Passwd(char* recv_buf,char* send_buf)
{
	//获取接收信息
	info* r_info = (info*)recv_buf;
	//验证账户密码（暂时省略这一步）
	string name = r_info->name;
	string passwd = r_info->passwd;
	string new_passwd = r_info->newpasswd;
	//构造修改密码SQL语句
	string sql = "update user set passwd = '";
	sql = sql + new_passwd + "' where username = '" + name + "' and passwd = '" + passwd + "';";
	//更新数据库
	bool isExe = Database().query_SQL((char*)sql.data());
	//根据查询到的结果进行反馈
	info* s_info = (info*)send_buf;

	//执行成功
	if(isExe)
	{
		//tlog.get_Log_Ptr() << name << "充值成功,余额为:" << charge_num << endl;
		s_info->status_code = _CHANGE_PASSWD_OK;
	}
	else
	{
		cout << name << "修改密码失败" << endl;
		s_info->status_code = _CHANGE_PASSWD_ERROR;
	}
}

void Parse::deal_Search_Commodity(char* recv_buf,char* send_buf)
{
	//日志文件
	Log tlog;
	//获取接收信息
	info* r_info = (info*)recv_buf;
	//获取用户名
	string uname = r_info->name;
	tlog.get_Log_Ptr() << uname << "请求检索" << endl;
	//根据查询方式进行不同的查询
	int search_way = r_info->searchcode;
	string sql = "select * from goods where "; //查询
	string app_str; //查询的条件
	cout << "length:" << sizeof(*r_info) << endl;
	cout << "opcode:" << r_info->opcode << endl;
	cout << "searchcode:" << r_info->searchcode << endl;
	switch (search_way)
	{
	case SEARCH_PRICE:
		{
			app_str = "price > " + to_string(r_info->min_price) + " and price < " + to_string(r_info->max_price);
			tlog.get_Log_Ptr() << "检索方式：价格 " << "检索关键词 " 
							<< "最低价格：" <<  r_info->min_price 
							<< " 最高价格：" << r_info->max_price << endl;
			break;
		}
	case SEARCH_CLASS:
		{
			cout << "r_info->classify:" << r_info->classify << endl;
			string classify = r_info->classify;
			app_str = "classify = '" + classify + "';";
			tlog.get_Log_Ptr() << "检索方式：类别 " << "检索关键词:" << r_info->classify << endl;
			break;
		}
	case SEARCH_NAME:
		{
			string name = r_info->sc_name;
			app_str = "name = '" + name + "';";
			tlog.get_Log_Ptr() << "检索方式：名称 " << "检索关键词:" << r_info->sc_name << endl;
			break;
		}
	default:
		break;
	}
	cout << "app_str:" << app_str << endl;
	sql = sql + app_str;
	cout << "sql = " << sql << endl;
	char* csql = (char*)sql.data();
	//返回的信息
	info* s_info = (info*)send_buf;

	//检索到的商品数目
	int fnum;
	fnum = Database().get_All_Commodity_Info(*s_info,csql);

	tlog.get_Log_Ptr() << "检索结果：" << fnum << "个" << endl;
	//cout << "fnum:" << fnum << endl << endl;
	s_info->com_num = fnum;
}

void Parse::deal_Search_Single_Commodity(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;
	//获取接收信息
	info* r_info = (info*)recv_buf;	

	//获取姓名
	string name = r_info->name;
	//获取identifier
	int iden = r_info->identifier;
	tlog.get_Log_Ptr() << name << "请求查询identifier = " << iden << " 的商品" << endl; 
	
	//构造查询SQL语句
	string sql = "select * from goods where "; //查询
	string app_sql = "identifier = " + to_string(iden) + ";";
	sql += app_sql;
	//cout << "sql:" << sql << endl;

	//返回的信息
	info* s_info = (info*)send_buf;
	//转char*
	char* cstr = (char*)sql.data();
	//fnum:查到的结果数目
	int fnum = Database().get_All_Commodity_Info(*s_info,cstr);
	s_info->com_num = fnum;
	tlog.get_Log_Ptr() << "查询到" << fnum << "个商品" << endl;
}

void Parse::deal_Add_Cart(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;
	//获取接收信息
	info* r_info = (info*)recv_buf;	
	
	//更新user表的数据,cartnum,cartIndexArray,indexNumArray
	string sql_user = "update user set cartnum = ";
	int cartnum = r_info->cartnum;
	string cartIndexArray;
	string indexNumArray;
	for(int i=0; i<cartnum; i++)
	{
		cartIndexArray = cartIndexArray + to_string(r_info->cartIndexArray[i]) + ",";
		indexNumArray = indexNumArray + to_string(r_info->indexNumArray[i]) + ",";
	}
	string name = r_info->name;
	//组合sql语句
	sql_user = sql_user + to_string(cartnum) + " , cartIndexArray = '" 
			+ cartIndexArray + "' , indexNumArray = '" + indexNumArray + "' "
			+ "where username = '" + name + "';";
	cout << "sql_user:" << sql_user << endl;
	tlog.get_Log_Ptr() << name << "请求添加购物车 商品id:" 
					<< r_info->cartIndexArray[cartnum-1] << " 添加商品数目:" 
					<< r_info->indexNumArray[cartnum-1] << endl;
	//更新goods表数据
	string sql_goods = "update goods set remain = ";
	int remain = r_info->remain_num;
	int frozen = r_info->frozen_num;
	int iden = r_info->identifier;
	//组合sql语句
	sql_goods = sql_goods + to_string(remain) + " , frozen = " 
			+ to_string(frozen) + " where identifier = " + to_string(iden) + ";";
	cout << "sql_goods:" << sql_goods << endl;

	//分别执行sql语句
	bool ruser = Database().query_SQL((char*)sql_user.data());
	bool rgoods = Database().query_SQL((char*)sql_goods.data());

	info* s_info = (info*)send_buf; 
	if(ruser && rgoods)
	{
		tlog.get_Log_Ptr() << "添加购物车成功" << endl;
		s_info->status_code = _ADD_CART_OK;
	}
	else
	{
		tlog.get_Log_Ptr() << "添加购物车失败" << endl;
		s_info->status_code = _ADD_CART_ERROR;
	}
}

void Parse::deal_Modify_Cart(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;
	//获取接收信息
	info* r_info = (info*)recv_buf;	
	
	//更新user表的数据,cartnum,cartIndexArray,indexNumArray
	string sql_user = "update user set ";
	int cartnum = r_info->cartnum;
	string cartIndexArray;
	string indexNumArray;
	for(int i=0; i<cartnum; i++)
	{
		cartIndexArray = cartIndexArray + to_string(r_info->cartIndexArray[i]) + ",";
		indexNumArray = indexNumArray + to_string(r_info->indexNumArray[i]) + ",";
	}
	string name = r_info->name;
	//组合sql语句
	sql_user = sql_user + " cartIndexArray = '" 
			+ cartIndexArray + "' , indexNumArray = '" + indexNumArray + "' "
			+ "where username = '" + name + "';";
	cout << "sql_user:" << sql_user << endl;
	
	
	//更新goods表数据
	string sql_goods = "update goods set remain = ";
	int remain = r_info->remain_num;
	int frozen = r_info->frozen_num;
	int iden = r_info->identifier;
	//组合sql语句
	sql_goods = sql_goods + to_string(remain) + " , frozen = " 
			+ to_string(frozen) + " where identifier = " + to_string(iden) + ";";
	cout << "sql_goods:" << sql_goods << endl;

	tlog.get_Log_Ptr() << name << "请求修改购物车"  << endl;
	//分别执行sql语句
	bool ruser = Database().query_SQL((char*)sql_user.data());
	bool rgoods = Database().query_SQL((char*)sql_goods.data());

	info* s_info = (info*)send_buf; 
	if(ruser && rgoods)
	{
		tlog.get_Log_Ptr() << "修改购物车成功" << endl;
		s_info->status_code = _MODIFY_CART_OK;
	}
	else
	{
		tlog.get_Log_Ptr() << "修改购物车失败" << endl;
		s_info->status_code = _MODIFY_CART_ERROR;
	}
}

void Parse::deal_Create_Order(char* recv_buf,char* send_buf)
{
	//创建数据库对象
	Database db;

	//日志
	Log tlog;
	//获取接收信息
	info* r_info = (info*)recv_buf;	
	info* s_info = (info*)send_buf;
	//用户名
	string name = r_info->name;
	tlog.get_Log_Ptr() << name << "请求支付订单" << endl;

	/*构造sql语句 修改用户购物车及余额，修改商家余额，修改商品冻结量*/

	//修改用户购物车及余额
	string sql_user = "update user set ";
	int cartnum = r_info->cartnum;
	string cartIndexArray;
	string indexNumArray;
	for(int i=0; i<cartnum; i++)
	{
		cartIndexArray = cartIndexArray + to_string(r_info->cartIndexArray[i]) + ",";
		indexNumArray = indexNumArray + to_string(r_info->indexNumArray[i]) + ",";
	}
	sql_user = sql_user + " cartIndexArray = '" + cartIndexArray 
			+ "' , indexNumArray = '" + indexNumArray 
			+ "', balance = " + to_string(r_info->newbalance)
			+ " ,cartnum = " + to_string(r_info->cartnum)
			+ " where username = '" + name + "';";
	cout << "sql_user:" << sql_user << endl;
	db.query_SQL((char*)sql_user.data());

	//修改商家余额
	//获取商家当前余额
	string admin_name = "admin";
	double admin_cur_balance = Database().get_User_Balance(admin_name);
	if(admin_cur_balance == -1)
	{
		cout << "没有查询到该人" << endl;
		s_info->opcode = _CREATE_ORDER_PAY_ERROE;
		return;
	}
	// cout << "商家当前余额：" << admin_cur_balance << endl;
	admin_cur_balance += r_info->order_money;
	// cout << "商家的新余额：" << admin_cur_balance << endl;
	string sql_admin = "update user set balance = ";
	sql_admin = sql_admin + to_string(admin_cur_balance) + " where username = 'admin';";
	cout << "sql_admin:" << sql_admin << endl;
	db.query_SQL((char*)sql_admin.data());
	tlog.get_Log_Ptr() << "订单总金额：" << r_info->order_money << endl;
	//修改商品冻结数目，多条SQL语句
	for(int i=0; i<r_info->com_num; i++)
	{
		// cout << "i = " << i << " r_info->com_array[i].identifier = " 
		// 	<< r_info->com_array[i].identifier << "frozen_sub = " << r_info->com_array[i].frozen << endl;
		//获取商品信息
		commodity com;
		int isFind = Database().get_Com_Info(r_info->com_array[i].identifier,com);
		if(!isFind)
		{
			cout << "商品信息出错" << endl;
			return;
		}
		tlog.get_Log_Ptr() << "订单商品编号：" << i+1 << endl
							<< "商品id：" << com.identifier << endl
							<< "商品名称：" << com.cname << endl
							<< "订单商品数目：" << r_info->com_array[i].frozen << endl;
		// cout << "id = " << r_info->com_array[i].identifier << " identifier:" << com.identifier << " frozen_num:" << com.frozen << endl;
		int cur_frozen = com.frozen - r_info->com_array[i].frozen;
		string sql_com = "update goods set frozen = ";
		sql_com = sql_com + to_string(cur_frozen) + " where identifier = " + to_string(com.identifier) + ";";
		cout << "sql_com:" << sql_com << endl;
		db.query_SQL((char*)sql_com.data());
	}

	//所有SQL语句准备并执行完毕，sql_user,sql_admin,sql_com
	// 返回信息
	s_info->status_code = _CREATE_ORDER_PAY_OK;
}

void Parse::deal_Add_Commodity(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;
	tlog.get_Log_Ptr() << "admin请求添加商品" << endl;
	info* r_info = (info*)recv_buf;
	cout << "收到的商品" << endl;
	{
		// cout << r_info->com_array[0].identifier << endl
		// << r_info->com_array[0].cname << endl
		// << r_info->com_array[0].brand << endl
		// << r_info->com_array[0].classify << endl
		// << r_info->com_array[0].price << endl
		// << r_info->com_array[0].remain << endl
		// << r_info->com_array[0].frozen << endl
		// << r_info->com_array[0].others << endl;
	}
	string sql = "insert into goods (identifier,name,brand,classify,price,remain,frozen,others) values(";
	sql = sql + to_string(r_info->com_array[0].identifier)
		+ ",'" + (string)r_info->com_array[0].cname
		+ "','" + (string)r_info->com_array[0].brand
		+ "','" + (string)r_info->com_array[0].classify
		+ "'," + to_string(r_info->com_array[0].price)
		+ "," + to_string(r_info->com_array[0].remain)
		+ "," + to_string(r_info->com_array[0].frozen)
		+ ",'" + (string)r_info->com_array[0].others + "');";
	tlog.get_Log_Ptr() << "添加的商品:" << sql << endl;
	//执行SQL
	bool isQuery = Database().query_SQL((char*)sql.data());
	info* s_info = (info*)send_buf;
	if(isQuery)
	{
		tlog.get_Log_Ptr() << "添加成功" << endl;
		s_info->status_code = _ADD_COMMODITY_OK;
	}
	else
	{
		tlog.get_Log_Ptr() << "添加失败" << endl;
		s_info->status_code = _ADD_COMMODITY_ERROR;
	}
}

void Parse::deal_Modify_Commodity(char* recv_buf,char* send_buf)
{
	//日志
	Log tlog;
	tlog.get_Log_Ptr() << "admin请求修改商品信息" << endl;
	//接收信息
	info* r_info = (info*)recv_buf;
	{
		// cout << r_info->com_array[0].identifier << endl
		// << r_info->com_array[0].cname << endl
		// << r_info->com_array[0].brand << endl
		// << r_info->com_array[0].classify << endl
		// << r_info->com_array[0].price << endl
		// << r_info->com_array[0].remain << endl
		// << r_info->com_array[0].frozen << endl
		// << r_info->com_array[0].others << endl;
	}
	//构造SQL语句
	string sql = "update goods set";
	sql = sql + " name = '" + (string)r_info->com_array[0].cname
		+ "', brand = '" + (string)r_info->com_array[0].brand
		+ "', classify = '" + (string)r_info->com_array[0].classify
		+ "', price = " + to_string(r_info->com_array[0].price)
		+ ", remain = " + to_string(r_info->com_array[0].remain)
		+ ", others = '" + (string)r_info->com_array[0].others
		+ "' where identifier = " + to_string(r_info->com_array[0].identifier) + ";";
	tlog.get_Log_Ptr() << "修改请求如下:" << sql << endl;

	//执行SQL语句
	bool isQuery = Database().query_SQL((char*)sql.data());
	info* s_info = (info*)send_buf;
	if(isQuery)
	{
		tlog.get_Log_Ptr() << "修改成功" << endl;
		s_info->status_code = _MODIFY_COMMODITY_OK;
	} 
	else
	{
		tlog.get_Log_Ptr() << "修改失败" << endl;
		s_info->status_code = _MODIFY_COMMODITY_ERROR;
	}
}
